<template>
  <div class="grille-container">
    <div class="paper-title">
      <!-- 试卷标题 -->
      <div class="paper-title-name">
        <div class="paper-name">
          {{ formModel.paperName }}
        </div>
        <el-divider />
        <div class="paper-total">
          总题数 <span>{{ formModel.questionCount }}</span> 题，共 <span>{{ formModel.totalScore }}</span> 分
        </div>
      </div>
      <el-divider />
      <el-descriptions :column="1">
        <el-descriptions-item label="作答时间">{{ formModel.answerTime }} 分钟</el-descriptions-item>
        <el-descriptions-item label="合格标准">{{ formModel.passPercentage }}%</el-descriptions-item>
        <el-descriptions-item label="合格分数">{{ formModel.passScore }}分</el-descriptions-item>
        <el-descriptions-item label="题目乱序"><span v-if="formModel.questionDerangement">开启</span> <span v-if="!formModel.questionDerangement">关闭</span></el-descriptions-item>
        <el-descriptions-item label="选项乱序"><span v-if="formModel.optionDerangement">开启</span> <span v-if="!formModel.optionDerangement">关闭</span></el-descriptions-item>
        <el-descriptions-item label="随机组卷"><span v-if="formModel.randomCombine">开启</span> <span v-if="!formModel.randomCombine">关闭</span></el-descriptions-item>
      </el-descriptions>
      <el-divider />
      <div class="but-set">
        <el-button v-permission="'paper:edit'" type="primary" plain size="large" @click="openFormModal(formModel)"> 试卷编辑 </el-button>
        <el-button v-permission="'paper:edit'" type="primary" plain size="large" style="float: right" @click="openScore()"> 分值批量设置 </el-button>
        <el-button v-permission="'paper:edit'" type="primary" plain size="large" style="float: right" @click="openRule()"> 组卷规则设置 </el-button>
      </div>
    </div>
    <div class="main-container">
      <div class="form-container paper-content">
        <!-- 试卷内容 -->
        <el-form ref="formRef" :model="formModel" @submit.prevent>
          <div v-for="(item, index) in formModel.paperTitles" :key="index" class="big-question" :name="index + 1">
            <div class="big-question-title">
              <div class="question-title">
                <!-- 大题折叠功能 -->
                <el-icon v-if="item.bigQuestionIsHide" @click="item.bigQuestionIsHide = !item.bigQuestionIsHide">
                  <ArrowRight />
                </el-icon>
                <el-icon v-if="!item.bigQuestionIsHide" @click="item.bigQuestionIsHide = !item.bigQuestionIsHide">
                  <ArrowDown />
                </el-icon>
                <!-- 大题标题 -->
                <div v-if="!item.titleNameIsEdit" class="title">
                  &nbsp;&nbsp; {{ formModel.paperTitles[index].titleName }} &nbsp;
                  <el-icon @click="item.titleNameIsEdit = !item.titleNameIsEdit">
                    <Edit />
                  </el-icon>
                </div>
                <div v-if="item.titleNameIsEdit">
                  <el-input v-if="item.titleNameIsEdit" v-model="formModel.paperTitles[index].titleName" :maxlength="15" show-word-limit>
                    <template #append>
                      <el-icon @click="item.titleNameIsEdit = !item.titleNameIsEdit">
                        <Check />
                      </el-icon>
                    </template>
                  </el-input>
                </div>
              </div>
              <div class="question-but">
                <el-button type="primary" @click="questionSelect(index, 1)">手工选题</el-button>
                <el-button type="primary" @click="questionSelect(index, 2)">系统抽题</el-button>
                <!-- 大题删除功能 -->
                <el-icon style="margin-left: 20px" @click="handleDelBigQuestion(index)">
                  <Delete />
                </el-icon>
              </div>
            </div>
            <div v-if="!item.bigQuestionIsHide">
              <div v-if="formModel.paperTitles[index].paperQuestions.length > 0" class="big-question-content">
                <div v-for="(itemSub, indexSub) in formModel.paperTitles[index].paperQuestions" :key="indexSub" class="question-content">
                  <div class="question-content-title">
                    <div class="content-title">
                      <!-- 小题题目 -->
                      <span>{{ indexSub + 1 }}.【<enum-view :enum-name="'QuestionType'" :enum-value="itemSub.questionType" />】 &nbsp;</span>
                      <div class="title-content" v-html="itemSub.questionTitle"></div>
                    </div>
                    <div class="content-icon">
                      <!-- 小题操作按钮 -->
                      <el-icon v-if="indexSub > 0" @click="handleTopQuestion(itemSub, index, indexSub)">
                        <Top />
                      </el-icon>
                      <el-icon v-if="indexSub < formModel.paperTitles[index].paperQuestions.length - 1" @click="handleBotQuestion(itemSub, index, indexSub)">
                        <Bottom />
                      </el-icon>
                      <el-icon @click="handleDelQuestion(index, indexSub)">
                        <Delete />
                      </el-icon>
                    </div>
                  </div>
                  <div class="question-content-score">
                    <!-- 分值设置 -->
                    <span>分值 <el-input-number v-model="itemSub.questionScore" class="min-number" controls-position="right" :precision="2" :min="0" /> 分</span>
                    <span v-if="itemSub.questionType === 2" style="margin-left: 10px">
                      <!-- 多选题 -->
                      <el-radio-group v-model="itemSub.multiScoreWay">
                        <el-radio :value="1">漏选得&nbsp;<el-input-number v-model="itemSub.multiScore" class="min-number" controls-position="right" :precision="2" :min="0" /> 分</el-radio>
                        <el-radio :value="2">每个正确得&nbsp;<el-input-number v-model="itemSub.multiScore" class="min-number" controls-position="right" :precision="2" :min="0" /> 分</el-radio>
                      </el-radio-group>
                    </span>
                    <span v-if="itemSub.questionType === 4" style="margin-left: 10px">
                      <!-- 填空题 -->
                      <el-radio-group v-model="itemSub.fillScoreWay">
                        <el-radio :value="2">每空&nbsp;<el-input-number v-model="itemSub.fillScore" class="min-number" controls-position="right" :precision="2" :min="0" /> 分</el-radio>
                      </el-radio-group>
                      <span class="tip">当填空题有多个空时，对一个得分</span>
                    </span>
                  </div>
                </div>
              </div>
              <el-result v-else sub-title="当前大题内容空空如也，可点击右上方按钮添加试题" />
            </div>
          </div>
          <el-button class="button-plus" :icon="Plus" @click="handleAddBigQuestion()"> 创建新的大题</el-button>
        </el-form>
        <div class="form-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="onSubmit()">保存</el-button>
        </div>
      </div>
    </div>
  </div>
  <!-- 手工选题 -->
  <select-manual v-if="question.manualVisible" :visible="question.manualVisible" :exclude-ids="question.selectIds" @close="handleQuestion" />
  <!-- 系统抽题 -->
  <select-random v-if="question.randomVisible" :visible="question.randomVisible" :exclude-ids="question.selectIds" @close="handleQuestion" />
  <!-- 分值设置 -->
  <set-score ref="setScoreRef" @refresh="handleScore" />
  <!-- 组卷规则 -->
  <set-rule ref="setRuleRef" @refresh="handleRule" />
  <!-- 试卷编辑 -->
  <paper-form ref="formRef" @refresh="handleDetail()" />
</template>
<script setup>
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { onMounted, reactive, ref } from 'vue'
  import { questionApi } from '@/api/question.js'
  import { useRouter } from 'vue-router'
  import { useRoute } from 'vue-router/dist/vue-router'
  import { ArrowDown, ArrowRight, Check, Edit, Plus } from '@element-plus/icons-vue'
  import { cloneDeep, numToChinese } from '@/utils/base.js'
  import { getEnumList } from '@/utils/enum'
  import EnumView from '@/components/Enum/View/index.vue'
  import SelectManual from './SelectManual.vue'
  import SelectRandom from './SelectRandom.vue'
  import SetScore from './SetScore.vue'
  import SetRule from './SetRule.vue'
  import PaperForm from '../PaperForm.vue'

  const router = useRouter()
  const defaultScore = 2 // 题目默认分值，用于计算分数

  // 选题功能
  const question = reactive({
    manualVisible: false,
    randomVisible: false,
    selectIndex: 0,
    selectIds: []
  })
  // 手工选题/系统抽题
  const questionSelect = (index, type) => {
    formModel.paperTitles.forEach((questions) => {
      questions.paperQuestions.forEach((itemSub) => {
        question.selectIds.push(itemSub.questionId)
      })
    })
    if (type === 1) {
      question.manualVisible = true
    }
    if (type === 2) {
      question.randomVisible = true
    }
    question.selectIndex = index
  }
  const handleQuestion = (questions, type) => {
    if (questions) {
      questions.forEach((item) => {
        item.multiScoreWay = 1 // 多选题得分方式(1:设置漏选得分、2:每个正确选项得分)
        item.multiScore = 0
        item.fillScoreWay = 1 // 填空题得分方式(1:每题得分、2:每空得分)
        item.fillScore = 0
        item.questionScore = defaultScore
      })
      formModel.paperTitles[question.selectIndex].paperQuestions.push(...questions)

      // 计算试卷总题数和总分
      paperStat()
    }
    if (type === 1) {
      question.manualVisible = false
    }
    if (type === 2) {
      question.randomVisible = false
    }
    question.selectIds = []
  }

  // 删除小题
  const handleDelQuestion = (index, indexSub) => {
    formModel.paperTitles[index].paperQuestions.splice(indexSub, 1)
    // 计算总题数和总分值
    paperStat()
  }
  // 上移小题
  const handleTopQuestion = (item, index, indexSub) => {
    if (indexSub > 0) {
      formModel.paperTitles[index].paperQuestions.splice(indexSub, 1)
      formModel.paperTitles[index].paperQuestions.splice(indexSub - 1, 0, item)
    }
  }
  // 下移小题
  const handleBotQuestion = (item, index, indexSub) => {
    if (indexSub < formModel.paperTitles[index].paperQuestions.length - 1) {
      formModel.paperTitles[index].paperQuestions.splice(indexSub, 1)
      formModel.paperTitles[index].paperQuestions.splice(indexSub + 1, 0, item)
    }
  }
  // 添加大题
  const handleAddBigQuestion = () => {
    const index = formModel.paperTitles.length
    formModel.paperTitles.push({
      titleName: '第' + numToChinese(index + 1) + '大题',
      singleChoiceCount: 0,
      multipleChoiceCount: 0,
      judgmentCount: 0,
      gapFillingCount: 0,
      shortAnswerCount: 0,
      materialCount: 0,
      paperQuestions: []
    })
  }
  // 删除大题
  const handleDelBigQuestion = (index) => {
    if (formModel.paperTitles.length <= 1) {
      ElMessage.warning('需至少保留一个大题')
      return
    }
    ElMessageBox.confirm('确认是否删除该大题？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      formModel.paperTitles.splice(index, 1)
    })
  }

  // 分值批量设置
  const paperScore = reactive({})
  const setScoreRef = ref()
  const openScore = async () => {
    // 统计整张试卷的题型数量
    paperScore.questionTypeList.forEach((item) => {
      item.questionSum = 0
    })
    formModel.paperTitles.forEach((item) => {
      item.paperQuestions.forEach((itemSub) => {
        paperScore.questionTypeList[itemSub.questionType - 1].questionSum++
      })
    })
    setScoreRef.value.onOpen(paperScore)
  }
  // 分值设置回调
  const handleScore = (scoreModel) => {
    Object.assign(paperScore, scoreModel)
    // 总分
    formModel.totalScore = paperScore.totalScore
    // 分数设置
    formModel.paperTitles.forEach((item) => {
      item.paperQuestions.forEach((itemSub) => {
        itemSub.questionScore = paperScore.questionTypeList[itemSub.questionType - 1].questionScore
      })
    })
  }

  // 组卷规则设置功能
  const setRuleRef = ref()
  const openRule = async () => {
    formModel.paperTitles.forEach((item) => {
      item.singleChoiceCountSum = 0
      item.multipleChoiceCountSum = 0
      item.judgmentCountSum = 0
      item.gapFillingCountSum = 0
      item.shortAnswerCountSum = 0
      item.materialCountSum = 0
      item.paperQuestions.forEach((itemSub) => {
        if (itemSub.questionType === 1) {
          item.singleChoiceCountSum++
        }
        if (itemSub.questionType === 2) {
          item.multipleChoiceCountSum++
        }
        if (itemSub.questionType === 3) {
          item.judgmentCountSum++
        }
        if (itemSub.questionType === 4) {
          item.gapFillingCountSum++
        }
        if (itemSub.questionType === 5) {
          item.shortAnswerCountSum++
        }
        if (itemSub.questionType === 6) {
          item.materialCountSum++
        }
      })
    })
    setRuleRef.value.onOpen(formModel)
  }
  // 规则设置回调
  const handleRule = async (ruleModel) => {
    Object.assign(formModel, ruleModel)
    // 试卷规则更新
    const paperEdit = cloneDeep(formModel)
    delete paperEdit.paperTitles
    await questionApi.paperEdit(paperEdit)
  }

  // 试卷信息编辑
  const formRef = ref()
  const openFormModal = (item) => {
    formRef.value.onOpen(item)
  }

  // 表单
  const loading = ref(false) // 加载进度状态
  const emit = defineEmits(['refresh'])
  const formDefault = {
    id: undefined,
    paperTitles: []
  }
  const formModel = reactive({ ...formDefault })
  // 保存
  const onSubmit = async () => {
    if (loading.value === true) {
      ElMessage.warning('正在处理···')
      return
    }
    loading.value = true
    try {
      if (formModel.id) {
        await questionApi.paperCompose(formModel)
        ElMessage.success('组卷成功')
      }
      handleClose()
      emit('refresh')
    } finally {
      loading.value = false
    }
  }
  // 关闭
  const handleClose = () => {
    router.go(-1)
  }
  // 初始化
  const route = useRoute()
  onMounted(async () => {
    await handleDetail()
    // 获取题型
    paperScore.questionTypeList = await getEnumList('QuestionType')
    // 分值批量处理
    paperScore.questionTypeList.forEach((item) => {
      item.multiScoreWay = 1 // 多选题得分方式(1:设置漏选得分、2:每个正确选项得分)
      item.multiScore = 0
      item.fillScoreWay = 1 // 填空题得分方式(1:每题得分、2:每空得分)
      item.fillScore = 0
      item.questionScore = defaultScore
      item.questionSum = 0
    })
  })

  // 计算试卷总题数和总分
  const paperStat = () => {
    formModel.questionCount = formModel.paperTitles.reduce((total, item) => {
      return total + item.paperQuestions.length
    }, 0)
    formModel.totalScore = formModel.paperTitles.reduce((total, item) => {
      return (
        total +
        item.paperQuestions.reduce((totalSub, itemSub) => {
          return totalSub + itemSub.questionScore
        }, 0)
      )
    }, 0)
  }
  // 试卷信息
  const handleDetail = async () => {
    if (route.query.paperId) {
      const res = await questionApi.paperDetailView({ id: route.query.paperId })
      Object.assign(formModel, res)
    } else {
      Object.assign(formModel, formDefault)
    }
    if (formModel.paperTitles.length === 0) {
      handleAddBigQuestion()
    }
  }
</script>
<style lang="scss" scoped>
  .big-question {
    border: 1px solid #ebeef5;
    margin-bottom: 20px;
    border-radius: 5px;

    .big-question-title {
      background-color: rgba(242, 243, 245, 0.8);
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding: 0 25px;
      height: 60px;

      .question-title {
        display: flex;
        align-items: center;

        .title {
          display: flex;
          align-items: center;
        }
      }

      .question-but {
        display: flex;
        align-items: center;
      }
    }

    .big-question-content {
      .question-content {
        border: 1px solid transparent;

        &:hover {
          border: 1px dashed #3d7fff;
        }

        .question-content-title {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 5px 25px;

          .content-title {
            display: flex;
            align-items: center;
            justify-content: flex-start;
            width: 100%;

            .title-content {
              display: flex;
              align-items: center;
              justify-content: space-between;
              width: calc(100% - 200px);
            }
          }

          .content-icon {
            width: 60px;
            display: flex;
            align-items: center;
            justify-content: flex-end;

            .el-icon {
              margin-right: 10px;
            }
          }
        }

        .question-content-score {
          padding: 10px 25px;
          background: rgba(242, 243, 245, 0.8);
          color: #606266;
          display: flex;
        }
      }
    }
  }

  .button-plus {
    width: 100%;
    height: 60px;
    margin-bottom: 60px;
    background: rgba(61, 127, 255, 0.1);
    border: 1px solid rgba(61, 127, 255, 0.6);
  }

  .left-content {
    width: 250px;
    padding-right: 20px;
  }

  .paper-title {
    width: 250px;

    .paper-title-name {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      flex: 1;

      .paper-name {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        font-weight: bolder;
      }

      .paper-total {
        text-align: center;
      }
    }

    .el-button {
      width: 100%;
      margin-bottom: 20px;
    }
  }

  .paper-content {
    padding-left: 10px;
    border-left: solid 1px #ebeef5;
    overflow: auto;
    height: 100%;

    .form-footer {
      width: calc(100vw - 545px);
      margin-bottom: 0;
      margin-left: 0;
    }
  }
</style>
